package com.jprocms.module.cms.controller.portal.page;

import com.jprocms.module.cms.dal.dataobject.channel.ChannelDO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.service.channel.ChannelService;
import com.jprocms.module.cms.service.site.SiteService;
import com.jprocms.module.cms.util.CommonParamValidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.jprocms.module.cms.constant.CmsSysConstants.CHANNEL_PREFIX;
import static com.jprocms.module.cms.constant.CmsSysConstants.TPL_PAGE_NOT_NOUNT;
import static com.jprocms.module.cms.controller.portal.page.ContentController.TPL_NOAUTH;
import static com.jprocms.module.cms.util.FrontContextUtil.*;

/**
 * 前台栏目 Controller
 *
 * @author jprocms
 */
@Slf4j
@Controller("channelFrontController")
public class ChannelController {

    @GetMapping({CHANNEL_PREFIX + "/{channelPath:[\\w-]+}", CHANNEL_PREFIX + "/{channelPath:[\\w-]+}/{page:[\\d]+}",
            "/{sitePath:[\\w-]+}" + CHANNEL_PREFIX + "/{channelPath:[\\w-]+}",
            "/{sitePath:[\\w-]+}" + CHANNEL_PREFIX + "/{channelPath:[\\w-]+}/{page:[\\d]+}",
            "/{customChannelPrefix:[\\w-]+}" + "/{channelPath:[^\\d]+}",
            "/{customChannelPrefix:[\\w-]+}" + "/{channelPath:[\\w-]+}/{page:[\\d]+}"
    })
    public String channel(@PathVariable String channelPath, @PathVariable(required = false) String sitePath,
                          @PathVariable(required = false) Integer page, HttpServletRequest request, Map<String, Object> modelMap) {
        SiteDO site = siteService.getSite(sitePath);
        ChannelDO channel = channelService.selectByChannelPath(channelPath, site.getId());
        if (channel == null) {
            log.error("Channel not found: siteId={}, channelPath=", site.getId(), channelPath);
            return site.joinTemplate(TPL_PAGE_NOT_NOUNT);
        }
        modelMap.put("channel", channel);
        modelMap.put(PAGE, CommonParamValidUtil.validPage(page));
        modelMap.put(PAGE_SIZE, channel.getChannelExt().getPageSize());
        modelMap.put(PAGE_URL_RESOLVER, channel);
        return channel.getTpl();
    }

    @GetMapping({"/no-auth", "/{sitePath:[\\w-]+}/no-auth"})
    public String noAuth(@PathVariable(required = false) String sitePath) {
        SiteDO site = siteService.getSite(sitePath);
        return site.joinTemplate(TPL_NOAUTH);
    }

    private final ChannelService channelService;
    private final SiteService siteService;

    public ChannelController(ChannelService channelService, SiteService siteService) {
        this.channelService = channelService;
        this.siteService = siteService;
    }
}
